package com.nq.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nq.common.ServerResponse;
import com.nq.common.entity.StStockTickerDetails;
import com.nq.common.entity.info.StockTickerListInfo;
import com.nq.config.StockPoll;
import com.nq.dao.*;
import com.nq.dao.fund.StFundKlineMapper;
import com.nq.dao.fund.StFundMapper;
import com.nq.dao.stock.StStockMapper;
import com.nq.dao.stock.StUserLevelMapper;
import com.nq.fund.FundSimulatorComponent;
import com.nq.fund.entity.StFund;
import com.nq.fund.entity.StFundKline;
import com.nq.fund.vo.StFundKlineVo;
import com.nq.pojo.*;

import com.nq.service.IStockMarketsDayService;
import com.nq.service.IStockOptionService;
import com.nq.service.IStockService;
import com.nq.service.IUserService;
import com.nq.stock.entity.StStock;
import com.nq.stock.entity.StStockTicker;
import com.nq.stock.entity.StUserLevel;
import com.nq.utils.HttpClientRequest;
import com.nq.utils.PropertiesUtil;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.utils.stock.pinyin.GetPyByChinese;
import com.nq.utils.stock.qq.QqStockApi;
import com.nq.utils.stock.sina.SinaStockApi;
import com.nq.utils.task.tsanghi.StocksComponent;
import com.nq.utils.translate.GoogleTranslateUtil;
import com.nq.vo.stock.*;
import com.nq.vo.stock.k.MinDataVO;
import com.nq.vo.stock.k.echarts.EchartsDataVO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.nq.utils.DateTimeUtil.getCurrentTimeMiao;
import static com.nq.utils.DateTimeUtil.getCurrentTimeMiaoZero;

@Service("iStockService")
public class StockServiceImpl implements IStockService {
    private static final Logger log = LoggerFactory.getLogger(StockServiceImpl.class);

    @Autowired
    StockMapper stockMapper;

    @Autowired
    RealTimeMapper realTimeMapper;

    @Autowired
    IStockMarketsDayService iStockMarketsDayService;

    @Autowired
    StockPoll stockPoll;

    @Autowired
    StockFuturesMapper stockFuturesMapper;

    @Autowired
    StockIndexMapper stockIndexMapper;

    @Autowired
    IUserService iUserService;
    @Resource
    private FundSimulatorComponent fundSimulatorComponent;

    @Autowired
    IStockOptionService iStockOptionService;
    @Resource
    private StStockMapper stStockMapper;
    @Resource
    private StocksComponent stocksComponent;
    @Resource
    private UserPositionMapper userPositionMapper;
    @Resource
    private StFundKlineMapper fundKlineMapper;
    @Resource
    private StUserLevelMapper userLevelMapper;
    @Resource
    private StUserLevelServiceImpl stUserLevelService;
    @Autowired
    private StFundMapper stFundMapper;



    @Override
    public ServerResponse fundKLineList(String fundCode, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, Integer.MAX_VALUE);

        List<StFundKline> list = stockMapper.fundKLineList(fundCode);

        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setList(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse queryFund(String fundCode) {
        StFundKlineVo fund = stockMapper.queryFund(fundCode);

        //  涨跌幅 open存储的是昨收价格  close存储的是今日价格
        String close = fund.getOpen();
        String open = fund.getClose();
        if (StringUtils.isBlank(close) && StringUtils.isBlank(open)) {
            fund.setUp("0.00");
            fund.setChange("0.00");
            return ServerResponse.createBySuccess(fund);
        }

        BigDecimal decimalOpen = new BigDecimal(open);
        BigDecimal decimalClose = new BigDecimal(close);

        // 涨跌幅比例
        BigDecimal up = decimalOpen.subtract(decimalClose)
                .divide(decimalClose, 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
        // 涨跌值
        BigDecimal change = decimalOpen.subtract(decimalClose);

        fund.setUp(up.toString());
        fund.setChange(change.toString());
        return ServerResponse.createBySuccess(fund);
    }

    @Override
    public ServerResponse getStStock(String code, HttpServletRequest request) {

        QueryWrapper<StStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        StStock stStock = stStockMapper.selectOne(queryWrapper);
        if (null == stStock) {
            return ServerResponse.createByErrorMsg("股票不存在[本地查询失败]！");
        }
        String market = stStock.getMarket();

        StStockTickerDetails tickerDetails = stocksComponent.queryDetailsByMarketAndCode(market, code);

        // stocksComponent.thirdInterfaceStatistic(StocksComponent.MINI_PRICES, "getStStock");

        if (null == tickerDetails) {
            return ServerResponse.createByErrorMsg("股票不存在[第三方接口查询失败]！");
        }
        StockTickerListInfo data = tickerDetails.getData();
        if (null == data) {
            return ServerResponse.createByErrorMsg("股票详情不存在[第三方接口查询失败]！");
        }

        StStockTicker ticker = new StStockTicker();
        ticker.setName(data.getName());
        ticker.setCode(data.getCode());
        ticker.setUp(data.getUp());
        ticker.setPrice(data.getPrice());
        return ServerResponse.createBySuccess(ticker);
    }

    @Override
    @Transactional
    public ServerResponse fundList(Integer pageNum, Integer pageSize, String changePercent, HttpServletRequest req) {
        User user = iUserService.getCurrentRefreshUser(req);
        if (user == null) {
            return ServerResponse.createBySuccessMsg("Please log in first.");
        }

        // 获取用户等级
        Integer userId = user.getId();
        Integer levelId = stUserLevelService.getUserLevelByUserId(userId);


        PageHelper.startPage(pageNum, pageSize);
        List<StFundKlineVo> list = stockMapper.fundList(levelId, changePercent);


        // 处理涨跌幅比例和涨跌幅的值
        for (StFundKlineVo kline : list) {

            String close = kline.getOpen();
            String open = kline.getClose();

            if(StringUtils.isBlank(close) && StringUtils.isBlank(open)){
                kline.setFundCode(kline.getCode());
                kline.setUp("0.00");
                kline.setChange("0.00");
                continue;
            }

            BigDecimal decimalOpen = new BigDecimal(open);
            BigDecimal decimalClose = new BigDecimal(close);

            // 涨跌幅比例
            BigDecimal up = decimalOpen.subtract(decimalClose)
                    .divide(decimalClose, 4, RoundingMode.HALF_DOWN)
                    .multiply(BigDecimal.valueOf(100));
            // 涨跌值
            BigDecimal change = decimalOpen.subtract(decimalClose);

            kline.setUp(up.toString());
            kline.setChange(change.toString());
        }

        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setList(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    public ServerResponse getMarket() {
        String market_url = PropertiesUtil.getProperty("sina.market.url");
        String result = null;
        try {
            result = HttpClientRequest.doGet(market_url);
        } catch (Exception e) {
            log.error("e = {}", e);
        }
        String[] marketArray = result.split(";");
        List<MarketVO> marketVOS = Lists.newArrayList();
        for (int i = 0; i < marketArray.length; i++) {
            String hqstr = marketArray[i];
            try {
                if (StringUtils.isNotBlank(hqstr)) {
                    hqstr = hqstr.substring(hqstr.indexOf("\"") + 1, hqstr.lastIndexOf("\""));
                    MarketVO marketVO = new MarketVO();
                    String[] sh01_arr = hqstr.split(",");
                    marketVO.setName(sh01_arr[0]);
                    marketVO.setNowPrice(sh01_arr[1]);
                    marketVO.setIncrease(sh01_arr[2]);
                    marketVO.setIncreaseRate(sh01_arr[3]);
                    marketVOS.add(marketVO);
                }
            } catch (Exception e) {
                log.error("str = {} ,  e = {}", hqstr, e);
            }
        }
        MarketVOResult marketVOResult = new MarketVOResult();
        marketVOResult.setMarket(marketVOS);
        return ServerResponse.createBySuccess(marketVOResult);
    }

    public ServerResponse getStock(int pageNum, int pageSize, String keyWords, String stockPlate, String stockType, HttpServletRequest request) {
        PageHelper.startPage(pageNum, pageSize);
        User user = iUserService.getCurrentRefreshUser(request);
        List<Stock> stockList = this.stockMapper.findStockListByKeyWords(keyWords, stockPlate, stockType, Integer.valueOf(0));

        List<StockListVO> stockListVOS = Lists.newArrayList();
        if (stockList.size() > 0)
            for (Stock stock : stockList) {
                StockListVO stockListVO = new StockListVO();

                if (stock.getStockType().contains("hk")) {
                    String hk = RedisShardedPoolUtils.get(stock.getStockGid(), 1);
                    stockListVO = SinaStockApi.otherStockListVO(hk);
                } else if (stock.getStockType().contains("us")) {
                    String us = RedisShardedPoolUtils.get(stock.getStockGid(), 2);
                    stockListVO = SinaStockApi.otherStockListVO(us);
                } else {
                    stockListVO = SinaStockApi.assembleStockListVO(SinaStockApi.getSinaStock(stock.getStockGid()));
                }

                if(StrUtil.isBlank(stockListVO.getName())) {
                    stockListVO.setName(stock.getStockName());
                }


                stockListVO.setCode(stock.getStockCode());
                stockListVO.setSpell(stock.getStockSpell());
                stockListVO.setGid(stock.getStockGid());
                BigDecimal day3Rate = (BigDecimal) selectRateByDaysAndStockCode(stock.getStockCode(), 3).getData();
                stockListVO.setDay3Rate(day3Rate);
                stockListVO.setStock_plate(stock.getStockPlate());
                stockListVO.setStock_type(stock.getStockType());
                //是否添加自选
                if (user == null) {
                    stockListVO.setIsOption("0");
                } else {
                    stockListVO.setIsOption(iStockOptionService.isMyOption(user.getId(), stock.getStockCode()));
                }
                stockListVOS.add(stockListVO);
            }
        PageInfo pageInfo = new PageInfo(stockList);
        pageInfo.setList(stockListVOS);
        return ServerResponse.createBySuccess(pageInfo);
    }

    public void z1() {
        this.stockPoll.z1();
    }

    public void z11() {
        this.stockPoll.z11();
    }

    public void z12() {
        this.stockPoll.z12();
    }

    public void z2() {
        this.stockPoll.z2();
    }

    public void z21() {
        this.stockPoll.z21();
    }

    public void z22() {
        this.stockPoll.z22();
    }

    public void z3() {
        this.stockPoll.z3();
    }

    public void z31() {
        this.stockPoll.z31();
    }

    public void z32() {
        this.stockPoll.z32();
    }

    public void z4() {
        this.stockPoll.z4();
    }

    public void z41() {
        this.stockPoll.z41();
    }

    public void z42() {
        this.stockPoll.z42();
    }

    public void h1() {
        this.stockPoll.h1();
    }

    public void h11() {
        this.stockPoll.h11();
    }

    public void h12() {
        this.stockPoll.h12();
    }

    public void h2() {
        this.stockPoll.h2();
    }

    public void h21() {
        this.stockPoll.h21();
    }

    public void h22() {
        this.stockPoll.h22();
    }

    public void h3() {
        this.stockPoll.h3();
    }

    public void h31() {
        this.stockPoll.h31();
    }

    public void h32() {
        this.stockPoll.h32();
    }


    public void bj1() {
        this.stockPoll.bj1();
    }

    public ServerResponse getDateline(HttpServletResponse response, String code) {
        if (StringUtils.isBlank(code))
            return ServerResponse.createByErrorMsg("");
        Stock stock = this.stockMapper.findStockByCode(code);
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        response.setHeader("Access-Control-Allow-Origin", "*");
        Date time = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String end = sdf.format(time);
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(2, -3);
        Date m = c.getTime();
        String mon = sdf.format(m);
        String methodUrl = "http://q.stock.sohu.com/hisHq?code=cn_" + code + "+&start=" + mon + "&end=" + end + "&stat=1&order=D";
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String line = null;
        EchartsDataVO echartsDataVO = new EchartsDataVO();
        try {
            URL url = new URL(methodUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "gbk"));
                StringBuilder result = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    result.append(line).append(System.getProperty("line.separator"));
                JSONArray jsonArray = JSONArray.fromObject(result.toString());
                JSONObject json = jsonArray.getJSONObject(0);
                JSONArray jsonArray1 = JSONArray.fromObject(json.get("hq"));
                Collections.reverse((List<?>) jsonArray1);
                double[][] values = (double[][]) null;
                Object[][] volumes = (Object[][]) null;
                String[] date = null;
                values = new double[jsonArray1.size()][5];
                volumes = new Object[jsonArray1.size()][3];
                date = new String[jsonArray1.size()];
                for (int i = 0; i < jsonArray1.size(); i++) {
                    JSONArray js = JSONArray.fromObject(jsonArray1.get(i));
                    date[i] = js.get(0).toString();
                    values[i][0] = Double.valueOf(js.get(1).toString()).doubleValue();
                    values[i][1] = Double.valueOf(js.get(2).toString()).doubleValue();
                    values[i][2] = Double.valueOf(js.get(5).toString()).doubleValue();
                    values[i][3] = Double.valueOf(js.get(6).toString()).doubleValue();
                    values[i][4] = Double.valueOf(js.get(7).toString()).doubleValue();
                    volumes[i][0] = Integer.valueOf(i);
                    volumes[i][1] = Double.valueOf(js.get(7).toString());
                    volumes[i][2] = Integer.valueOf((Double.valueOf(js.get(3).toString()).doubleValue() > 0.0D) ? 1 : -1);
                }
                echartsDataVO.setDate(date);
                echartsDataVO.setValues(values);
                echartsDataVO.setVolumes(volumes);
                echartsDataVO.setStockCode(stock.getStockCode());
                echartsDataVO.setStockName(stock.getStockName());
//        log.info(String.valueOf(echartsDataVO));
                ServerResponse.createBySuccess(echartsDataVO);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection.disconnect();
        }
        return ServerResponse.createBySuccess(echartsDataVO);
    }

    public ServerResponse getSingleStock(String code, HttpServletRequest request) {
        if (StringUtils.isBlank(code))
            return ServerResponse.createByErrorMsg("请输入股票代码！");
        
        Stock stock = new Stock();
        Integer depositAmt = 0;
        String introduction = null;
        String result = null;
        com.alibaba.fastjson2.JSONObject json = null;
        //期货
        String url = null;
        if (code.contains("hf")) {
            StockFutures futmodel = stockFuturesMapper.selectFuturesByCode(code.replace("hf_", ""));
            stock.setStockGid(futmodel.getFuturesGid());
            stock.setStockCode(futmodel.getFuturesCode());
            stock.setStockName(futmodel.getFuturesName());
            stock.setAddTime(futmodel.getAddTime());
            stock.setId(futmodel.getId());
            stock.setStockSpell("0");
            depositAmt = futmodel.getDepositAmt();
            url = PropertiesUtil.getProperty("sina.single.futures.introduction.url") + futmodel.getFuturesCode() + "&app=source&type=1";
        } else if (code.contains("sh") || code.contains("sz") || code.contains("hk") || code.contains("us")) { //指数
            StockIndex model = stockIndexMapper.selectIndexByCode(code.replace("sh", "").replace("sz", "").replace("hk", "").replace("us", ""));
            stock.setStockGid(model.getIndexGid());
            stock.setStockCode(model.getIndexCode());
            stock.setStockName(model.getIndexName());
            stock.setAddTime(model.getAddTime());
            stock.setId(model.getId());
            stock.setStockSpell("0");
            depositAmt = model.getDepositAmt();
            introduction = model.getIntroduction();
        } else {//股票

            stock = this.stockMapper.findStockByCode(code);
            if (stock == null)
                return ServerResponse.createByErrorMsg("");

            //简介
            if (stock.getStockGid().contains("hk")) {
                url = PropertiesUtil.getProperty("hk.stock.introduction.url") + "%22" + stock.getStockCode() + ".HK%22)";
                result = HttpClientRequest.doGet(url);
                if (result.length() < 20) {
                    introduction = "No data yet";
                } else {
                    json = com.alibaba.fastjson2.JSONObject.parseObject(result);
                    introduction = json.getJSONObject("result").getJSONArray("data").getJSONObject(0).getString("ORG_PROFILE");
                    if (request.getHeader("lang") != null && !request.getHeader("lang").equals("zh-CN") && !request.getHeader("lang").equals("tww") && !request.getHeader("lang").equals("")) {
                        GoogleTranslateUtil googleTranslateUtil = new GoogleTranslateUtil();
                        try {
                            introduction = googleTranslateUtil.translate(introduction, request.getHeader("lang"));
                        } catch (Exception e) {
                            log.error("翻译失败");
                        }
                    }
                }
            } else {
                url = PropertiesUtil.getProperty("sina.single.stock.introduction.url") + stock.getStockGid();
                result = HttpClientRequest.doGet(url);
                json = com.alibaba.fastjson2.JSONObject.parseObject(result);
                //取json里result里的data里的introduction
                introduction = json.getJSONObject("result").getJSONObject("data").getString("introduction");
            }

        }
        String gid = stock.getStockGid();
        //股票数据
        StockVO stockVO = new StockVO();

        if (gid.contains("hk") && "hk".equals(stock.getStockType())) {
            String hkStock = RedisShardedPoolUtils.get(stock.getStockGid(), 1);
            stockVO = SinaStockApi.otherStockVO(hkStock);

        } else if (gid.contains("hk") || gid.contains("us")) {
            String index = RedisShardedPoolUtils.get(stock.getStockGid(), 3);
            stockVO = SinaStockApi.otherStockVO(index);
        } else {
            String sinaResult = SinaStockApi.getSinaStock(gid);

            if (code.contains("hf")) {
                stockVO = SinaStockApi.assembleStockFuturesVO(sinaResult);
            } else {
                stockVO = SinaStockApi.assembleStockVO(sinaResult);
            }
        }

//    if (stock.getDataBase()!=0){
//       String date = getCurrentTimeMiaoZero();
//      String result1 = HttpClientRequest.doGet(PropertiesUtil.getProperty("changePrice.url")+"?cat_time="+date+"&stock_gid="+stock.getStockGid()+"&price="+stockVO.getNowPrice());
//      JSONObject jsonObject = JSONObject.fromObject(result1);
//      String nowPrice = jsonObject.getJSONObject("data").getString("new_price");
//      if (nowPrice!=null){
//        stockVO.setNowPrice(nowPrice);
//      }else {
//        stockVO.setNowPrice(stockVO.getNowPrice());
//      }
//    }

        stockVO.setDepositAmt(depositAmt);
        stockVO.setId(stock.getId().intValue());
        stockVO.setCode(stock.getStockCode());
        stockVO.setSpell(stock.getStockSpell());
        stockVO.setGid(stock.getStockGid());
        stockVO.setMinImg(PropertiesUtil.getProperty("sina.single.stock.min.url") + stock.getStockGid() + ".jpg");
        stockVO.setDayImg(PropertiesUtil.getProperty("sina.single.stock.day.url") + stock.getStockGid() + ".jpg");
        stockVO.setWeekImg(PropertiesUtil.getProperty("sina.single.stock.week.url") + stock.getStockGid() + ".jpg");
        stockVO.setMonthImg(PropertiesUtil.getProperty("sina.single.stock.month.url") + stock.getStockGid() + ".jpg");
        Map map = Maps.newHashMap();
        map.put("introduction", introduction);
        map.put("stock", stockVO);
        return ServerResponse.createBySuccess(map);
    }


    //美股
    public ServerResponse getSingleStockByCode(String code) {
        if (StringUtils.isBlank(code))
            return ServerResponse.createByErrorMsg("");
        Stock stock = new Stock();
        Integer depositAmt = 0;
        String introduction = null;
        String result = null;
        com.alibaba.fastjson2.JSONObject json = null;
        //期货
        String url = null;
        if (code.contains("sh") || code.contains("sz")) { //指数
            StockIndex model = stockIndexMapper.selectIndexByCode(code.replace("sh", "").replace("sz", ""));
            stock.setStockGid(model.getIndexGid());
            stock.setStockCode(model.getIndexCode());
            stock.setStockName(model.getIndexName());
            stock.setAddTime(model.getAddTime());
            stock.setId(model.getId());
            stock.setStockSpell("0");
            depositAmt = model.getDepositAmt();
            introduction = model.getIntroduction();
        } else {//股票

            stock = this.stockMapper.findStockByCode(code);
            if (stock == null)
                return ServerResponse.createByErrorMsg("");
        }
        String gid = stock.getStockGid();
        StockUsVO stockVO = new StockUsVO();
        if (gid.contains("us")) {

            String us = RedisShardedPoolUtils.get(stock.getStockGid(), 2);
            stockVO = SinaStockApi.otherUsStockVO(us);
//      if (stock.getDataBase() != 0) {
////        String usOther = RedisShardedPoolUtils.get(stock.getStockName(), 8);
//         String date = getCurrentTimeMiaoZero();
//        //?+cat_time+=2022-11-22%2007:53:00&stock_gid=sz000001&price=10
//        String result1 = HttpClientRequest.doGet(PropertiesUtil.getProperty("changePrice.url")+"?cat_time="+date+"&stock_gid="+stock.getStockGid()+"&price="+stockVO.getNowPrice());
//        JSONObject jsonObject = JSONObject.fromObject(result1);
//        String nowPrice = jsonObject.getJSONObject("data").getString("new_price");
//        if (nowPrice!=null){
//          stockVO.setNowPrice(nowPrice);
//        }else {
//          stockVO.setNowPrice(stockVO.getNowPrice());
//        }
//      }
            String type = "105".equals(stockVO.getType()) ? ".O" : ".N";
            url = (PropertiesUtil.getProperty("us.stock.introduction.url") + stock.getStockCode() + type);
            result = HttpClientRequest.doGet(url);
            if (result.contains("msg")) {
                introduction = "No data yet";
            } else {
                json = com.alibaba.fastjson2.JSONObject.parseObject(result);
                if (json.getJSONObject("data").getJSONArray("gszl").size() > 0) {
                    introduction = json.getJSONObject("data").getJSONArray("gszl").getJSONObject(0).getString("COMPPROFILE");
                } else {
                    introduction = "No data yet";
                }

            }
        }
        /**
         * 105.UCL&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=%7C0%7C0%7C0%7Cweb&_=时间戳
         */
        long now = System.currentTimeMillis();
        com.alibaba.fastjson2.JSONObject buyjson = null;
        String buyresult = null;
        try {
            String buyurl = PropertiesUtil.getProperty("us.stock.buy.url") + stockVO.getType() + "." + stock.getStockCode() + "&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=%7C0%7C0%7C0%7Cweb&_=" + now;
            buyresult = HttpClientRequest.doGet(buyurl);
            buyjson = com.alibaba.fastjson2.JSONObject.parseObject(buyresult);
        } catch (Exception e) {
            log.error("获取分时交易数据失败", e);
            buyjson.put("data", "No data yet");
        }


        stockVO.setDepositAmt(depositAmt);
        stockVO.setId(stock.getId().intValue());
        stockVO.setCode(stock.getStockCode());
        stockVO.setSpell(stock.getStockSpell());
        stockVO.setGid(stock.getStockGid());
        Map map = Maps.newHashMap();
        map.put("timedata", buyjson);
        map.put("introduction", introduction);
        map.put("stock", stockVO);
        return ServerResponse.createBySuccess(map);
    }


    public ServerResponse getMinK(String code, Integer time, Integer ma, Integer size) {
        if (StringUtils.isBlank(code) || time == null || ma == null || size == null)
            return ServerResponse.createByErrorMsg("");
        Stock stock = this.stockMapper.findStockByCode(code);
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        return SinaStockApi.getStockMinK(stock, time.intValue(), ma.intValue(), size.intValue());
    }

    public ServerResponse getMinK_Echarts(String code, Integer time, Integer ma, Integer size) {
        if (StringUtils.isBlank(code) || time == null || ma == null || size == null)
            return ServerResponse.createByErrorMsg("");
        Stock stock = this.stockMapper.findStockByCode(code);
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        ServerResponse<MinDataVO> serverResponse = SinaStockApi.getStockMinK(stock, time.intValue(), ma.intValue(), size.intValue());
        MinDataVO minDataVO = (MinDataVO) serverResponse.getData();
        EchartsDataVO echartsDataVO = SinaStockApi.assembleEchartsDataVO(minDataVO);
        return ServerResponse.createBySuccess(echartsDataVO);
    }

    /*期货分时-k线*/
    public ServerResponse getFuturesMinK_Echarts(String code, Integer time, Integer size) {
        if (StringUtils.isBlank(code) || time == null)
            return ServerResponse.createByErrorMsg("");
        StockFutures stock = this.stockFuturesMapper.selectFuturesByCode(code.split("_")[1]);
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        ServerResponse<MinDataVO> serverResponse = SinaStockApi.getFuturesMinK(stock, time.intValue(), size.intValue());
        MinDataVO minDataVO = (MinDataVO) serverResponse.getData();
        EchartsDataVO echartsDataVO = SinaStockApi.assembleEchartsDataVO(minDataVO);
        return ServerResponse.createBySuccess(echartsDataVO);
    }

    /*指数分时-k线*/
    public ServerResponse getIndexMinK_Echarts(String code, Integer time, Integer size) {
        if (StringUtils.isBlank(code) || time == null)
            return ServerResponse.createByErrorMsg("");
        StockIndex stock = this.stockIndexMapper.selectIndexByCode(code.replace("sh", "").replace("sz", ""));
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        ServerResponse<MinDataVO> serverResponse = SinaStockApi.getIndexMinK(stock, time.intValue(), size.intValue());
        MinDataVO minDataVO = (MinDataVO) serverResponse.getData();
        EchartsDataVO echartsDataVO = SinaStockApi.assembleEchartsDataVO(minDataVO);
        return ServerResponse.createBySuccess(echartsDataVO);
    }

    /*股票日线-K线*/
    public ServerResponse getDayK_Echarts(String code) {
        if (StringUtils.isBlank(code))
            return ServerResponse.createByErrorMsg("");
        Stock stock = this.stockMapper.findStockByCode(code);
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        ServerResponse<MinDataVO> serverResponse = QqStockApi.getGpStockMonthK(stock, "day");
        MinDataVO minDataVO = (MinDataVO) serverResponse.getData();
        EchartsDataVO echartsDataVO = SinaStockApi.assembleEchartsDataVO(minDataVO);
        return ServerResponse.createBySuccess(echartsDataVO);
    }

    /*期货日线-K线*/
    public ServerResponse getFuturesDayK(String code) {
        if (StringUtils.isBlank(code))
            return ServerResponse.createByErrorMsg("");
        StockFutures stock = this.stockFuturesMapper.selectFuturesByCode(code.split("_")[1]);
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        ServerResponse<MinDataVO> serverResponse = QqStockApi.getQqStockDayK(stock);
        MinDataVO minDataVO = (MinDataVO) serverResponse.getData();
        EchartsDataVO echartsDataVO = SinaStockApi.assembleEchartsDataVO(minDataVO);
        return ServerResponse.createBySuccess(echartsDataVO);
    }

    /*指数日线-K线*/
    public ServerResponse getIndexDayK(String code) {
        if (StringUtils.isBlank(code))
            return ServerResponse.createByErrorMsg("");
        StockIndex stock = this.stockIndexMapper.selectIndexByCode(code.replace("sh", "").replace("sz", ""));
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        ServerResponse<MinDataVO> serverResponse = QqStockApi.getQqIndexDayK(stock);
        MinDataVO minDataVO = (MinDataVO) serverResponse.getData();
        EchartsDataVO echartsDataVO = SinaStockApi.assembleEchartsDataVO(minDataVO);
        return ServerResponse.createBySuccess(echartsDataVO);
    }

    public ServerResponse<Stock> findStockByName(String name) {
        return ServerResponse.createBySuccess(this.stockMapper.findStockByName(name));
    }

    public ServerResponse<Stock> findStockByCode(String code) {
        return ServerResponse.createBySuccess(this.stockMapper.findStockByCode(code));
    }

    public ServerResponse<Stock> findStockById(Integer stockId) {
        return ServerResponse.createBySuccess(this.stockMapper.selectByPrimaryKey(stockId));
    }

    public ServerResponse<PageInfo> listByAdmin(Integer showState, Integer lockState, String code, String name, String stockPlate, String stockType, int pageNum, int pageSize, HttpServletRequest request) {
        PageHelper.startPage(pageNum, pageSize);
        List<Stock> stockList = this.stockMapper.listByAdmin(showState, lockState, code, name, stockPlate, stockType);
        List<StockAdminListVO> stockAdminListVOS = Lists.newArrayList();
        for (Stock stock : stockList) {
            StockAdminListVO stockAdminListVO = assembleStockAdminListVO(stock);
            stockAdminListVOS.add(stockAdminListVO);
        }
        PageInfo pageInfo = new PageInfo(stockList);
        pageInfo.setList(stockAdminListVOS);
        return ServerResponse.createBySuccess(pageInfo);
    }

    private StockAdminListVO assembleStockAdminListVO(Stock stock) {
        StockAdminListVO stockAdminListVO = new StockAdminListVO();
        stockAdminListVO.setId(stock.getId());
        stockAdminListVO.setStockName(stock.getStockName());
        stockAdminListVO.setStockCode(stock.getStockCode());
        stockAdminListVO.setStockSpell(stock.getStockSpell());
        stockAdminListVO.setStockType(stock.getStockType());
        stockAdminListVO.setStockGid(stock.getStockGid());
        stockAdminListVO.setStockPlate(stock.getStockPlate());
        stockAdminListVO.setIsLock(stock.getIsLock());
        stockAdminListVO.setIsShow(stock.getIsShow());
        stockAdminListVO.setAddTime(stock.getAddTime());
        stockAdminListVO.setDataBase(stock.getDataBase());
        StockListVO stockListVO;
        if ("hk".equals(stock.getStockType())) {
            String hkStock = RedisShardedPoolUtils.get(stock.getStockGid(), 1);
            stockListVO = SinaStockApi.otherStockListVO(hkStock);
        } else if ("us".equals(stock.getStockType())) {
            String usStock = RedisShardedPoolUtils.get(stock.getStockGid(), 2);
            stockListVO = SinaStockApi.otherStockListVO(usStock);
        } else {
            stockListVO = SinaStockApi.assembleStockListVO(SinaStockApi.getSinaStock(stock.getStockGid()));
        }

//      String stockOther = RedisShardedPoolUtils.get(stock.getStockName(), 8);
//      if (stock.getDataBase()!=0){
//
//         String date = getCurrentTimeMiaoZero();
//        String result = HttpClientRequest.doGet(PropertiesUtil.getProperty("changePrice.url")+"?cat_time="+date+"&stock_gid="+stock.getStockGid()+"&price="+stockListVO.getNowPrice());
//        JSONObject jsonObject = JSONObject.fromObject(result);
//        String nowPrice = jsonObject.getJSONObject("data").getString("new_price");
//        if (nowPrice!=null){
//          stockListVO.setNowPrice(nowPrice);
//        }else {
//          stockListVO.setNowPrice(stockListVO.getNowPrice());
//        }
//      }

        stockAdminListVO.setNowPrice(stockListVO.getNowPrice());
        stockAdminListVO.setHcrate(stockListVO.getHcrate());
        stockAdminListVO.setSpreadRate(stock.getSpreadRate());
        ServerResponse serverResponse = selectRateByDaysAndStockCode(stock.getStockCode(), 3);
        BigDecimal day3Rate = new BigDecimal("0");
        if (serverResponse.isSuccess())
            day3Rate = (BigDecimal) serverResponse.getData();
        stockAdminListVO.setDay3Rate(day3Rate);
        return stockAdminListVO;
    }

    public ServerResponse updateLock(Integer stockId) {
        Stock stock = this.stockMapper.selectByPrimaryKey(stockId);
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        if (stock.getIsLock().intValue() == 1) {
            stock.setIsLock(Integer.valueOf(0));
        } else {
            stock.setIsLock(Integer.valueOf(1));
        }
        int updateCount = this.stockMapper.updateByPrimaryKeySelective(stock);
        if (updateCount > 0)
            return ServerResponse.createBySuccessMsg("success");
        return ServerResponse.createByErrorMsg("fail");
    }

    public ServerResponse updateShow(Integer stockId) {
        Stock stock = this.stockMapper.selectByPrimaryKey(stockId);
        if (stock == null)
            return ServerResponse.createByErrorMsg("");
        if (stock.getIsShow().intValue() == 0) {
            stock.setIsShow(Integer.valueOf(1));
        } else {
            stock.setIsShow(Integer.valueOf(0));
        }
        int updateCount = this.stockMapper.updateByPrimaryKeySelective(stock);
        if (updateCount > 0)
            return ServerResponse.createBySuccessMsg("success");
        return ServerResponse.createByErrorMsg("fail");
    }

    public ServerResponse addStock(String stockName, String stockCode, String stockType, String stockPlate, Integer isLock, Integer isShow) {
        if (StringUtils.isBlank(stockName) || StringUtils.isBlank(stockCode) || StringUtils.isBlank(stockType) || isLock == null || isShow == null)
            return ServerResponse.createByErrorMsg("Incorrect information filled in");
        Stock cstock = (Stock) findStockByCode(stockCode).getData();
        if (cstock != null)
            return ServerResponse.createByErrorMsg("The stock code is already available.");
        Stock nstock = (Stock) findStockByName(stockName).getData();
        if (nstock != null)
            return ServerResponse.createByErrorMsg("The name of the stock is already available.");
        String sinaStock = SinaStockApi.getSinaStock(stockType + stockCode);
        String[] arrayOfString = sinaStock.split(",");
//    if (arrayOfString.length < 10)
//      return ServerResponse.createByErrorMsg("数据源无该股票");

        Stock stock = new Stock();
        stock.setStockName(stockName);
        stock.setStockCode(stockCode);
        stock.setStockSpell(GetPyByChinese.converterToFirstSpell(stockName));
        stock.setStockType(stockType);
        stock.setStockGid(stockType + stockCode);
        stock.setIsLock(isLock);
        stock.setIsShow(isShow);
        stock.setAddTime(new Date());
        if (stockPlate != null)
            stock.setStockPlate(stockPlate);

        if (stockPlate != null && StringUtils.isNotEmpty(stockPlate) && stockCode.startsWith("300"))
            stock.setStockPlate("创业");
        else if (stockPlate != null && StringUtils.isNotEmpty(stockPlate) && stockCode.startsWith("688"))
            stock.setStockPlate("科创");
        else
            stock.setStockPlate(null);

        int insertCount = this.stockMapper.insert(stock);
        if (insertCount > 0)
            return ServerResponse.createBySuccessMsg("Added successfully");
        return ServerResponse.createByErrorMsg("Failed to add");
    }

    public int CountStockNum() {
        return this.stockMapper.CountStockNum();
    }

    public int CountShowNum(Integer showState) {
        return this.stockMapper.CountShowNum(showState);
    }

    public int CountUnLockNum(Integer lockState) {
        return this.stockMapper.CountUnLockNum(lockState);
    }

    public List findStockList() {
        return this.stockMapper.findStockList();
    }

    public ServerResponse selectRateByDaysAndStockCode(String stockCode, int days) {
        Stock stock = this.stockMapper.findStockByCode(stockCode);
        if (stock == null)
            return ServerResponse.createByErrorMsg("There is no such stock.");
        BigDecimal daysRate = this.iStockMarketsDayService.selectRateByDaysAndStockCode(stock.getId(), days);
        return ServerResponse.createBySuccess(daysRate);
    }

    public ServerResponse updateStock(Stock model) {
        if (StringUtils.isBlank(model.getId().toString()) || StringUtils.isBlank(model.getStockName()))
            return ServerResponse.createByErrorMsg("There is an error in modifying the information.");
        Stock stock = this.stockMapper.selectByPrimaryKey(model.getId());
        if (stock == null)
            return ServerResponse.createByErrorMsg("Stocks do not exist.");
        stock.setStockName(model.getStockName());
        if (model.getSpreadRate() != null)
            stock.setSpreadRate(model.getSpreadRate());

        int updateCount = this.stockMapper.updateByPrimaryKeySelective(stock);
        if (updateCount > 0)
            return ServerResponse.createBySuccessMsg("Successful modification");
        return ServerResponse.createByErrorMsg("Modification Failed");
    }

    public ServerResponse deleteByPrimaryKey(Integer id) {
        int updateCount = this.stockMapper.deleteByPrimaryKey(id);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("Operation successfully");
        }
        return ServerResponse.createByErrorMsg("Operation failed");
    }

    public ServerResponse stockDataBase() {
        //mybatisplus查询所有database 不是0的
        List<Stock> stockList = this.stockMapper.selectList(new QueryWrapper<Stock>().ne("data_base", 0));
        return ServerResponse.createBySuccess(stockList);
    }

    @Override
    public ServerResponse getZdfb() {
        return null;
    }

    @Override
    public ServerResponse getStockSort(Integer pageNo, Integer pageSize, String sort, Integer asc, String node) {
        return null;
    }


    /**
     * 涨停板
     * @return
     */
    @Override
    public ServerResponse ztb() {
        String day = getWeekDay();
        String url = PropertiesUtil.getProperty("ztb.url");
        //当前时间戳
//    log.info("当前时间戳：{}",day);
        //day去掉-
        String day1 = day.replace("-", "");
        long time = System.currentTimeMillis();
        url = url.replace("20221202", day1) + time;
//    log.info("涨停板接口：{}",url);
        String res = HttpClientRequest.doGet(url);

        com.alibaba.fastjson2.JSONObject json = com.alibaba.fastjson2.JSONObject.parseObject(res);
        com.alibaba.fastjson2.JSONArray pool = null;
        if (json.getJSONObject("data") != null) {
            pool = json.getJSONObject("data").getJSONArray("pool");
        }
        return ServerResponse.createBySuccess(pool);
    }

    private String getWeekDay() {
        return null;
    }

    @Override
    public ServerResponse getVipByCode(String code) {
        String day = getWeekDay();
        String url = PropertiesUtil.getProperty("ztb.url");
        String day1 = day.replace("-", "");
        long time = System.currentTimeMillis();
        url = url.replace("20221202", day1) + time;
//    log.info("涨停板接口：{}",url);
        String res = HttpClientRequest.doGet(url);

        com.alibaba.fastjson2.JSONObject json = com.alibaba.fastjson2.JSONObject.parseObject(res);
        com.alibaba.fastjson2.JSONArray pool = null;
        if (json.getJSONObject("data") != null) {
            pool = json.getJSONObject("data").getJSONArray("pool");
            if (pool != null) {
                for (int i = 0; i < pool.size(); i++) {
                    com.alibaba.fastjson2.JSONObject jsonObject = pool.getJSONObject(i);
                    String c = jsonObject.getString("c");
                    if (c.equals(code)) {
                        pool.removeAll(pool);
                        pool.add(jsonObject);
                        return ServerResponse.createBySuccess(pool);
                    }
                }
            }
        }
        return ServerResponse.createBySuccess(pool);
    }


}
